package com.motu.monstercity.server.game.logic;

import com.motu.monstercity.module.common.network.ResponseUtils;
import com.motu.monstercity.module.common.servermanager.ServerManager;
import com.motu.monstercity.module.common.utility.EventBusConstant;
import com.motu.monstercity.protocol.Common;
import com.motu.monstercity.protocol.Common.PBChatMsg;
import com.motu.monstercity.protocol.CsGameFeast.CSGameFeastPushDataResponse;
import com.motu.monstercity.protocol.CsGameSystem;
import com.motu.monstercity.protocol.CsGameSystem.CSGameSystemPushDataResponse;
import com.motu.monstercity.protocol.CsGameSystem.CSGameSystemRedPointResponse;
import com.motu.monstercity.protocol.CsGameWorld;
import com.motu.monstercity.server.game.base.ProtoDataUtils;
import com.motu.monstercity.server.game.userdata.*;
import com.motu.vertx.module.utility.main.MainService;
import com.motu.vertx.module.utility.model.EntityManager;
import com.motu.vertx.module.utility.toolset.Tool;
import io.vertx.core.eventbus.DeliveryOptions;
import io.vertx.core.eventbus.EventBus;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class BoardcastManager {
    public static final Logger logger = LoggerFactory.getLogger(BoardcastManager.class);

    /**
     * 广播派对聊天
     * @param userInfo 发言者
     * @param serverFeast 派对对象
     * @param msg 聊天内容
     *  @param keyId map的key 一般是dbid
     */
    public static void publicFeastMessage(UserInfo userInfo, ServerFeast serverFeast, PBChatMsg.Builder chatBuilder, long keyId) {
        long userId = userInfo.getId();
        String address = EventBusConstant.getAddress(EventBusConstant.GATE_BROADCAST);
        EventBus eventBus = MainService.getVertx().eventBus();
        DeliveryOptions options = new DeliveryOptions();
        options.addHeader("suid", userId + "");// 发言者的userid,广播时过滤
        JsonArray userList = new JsonArray();// 广播的对象
        JsonArray jsonArray = EntityManager.getEntityKeyList(ServerFeastSeat.class, serverFeast.getId());// 座位列表,参与派对的所有人的userid
        for (int i=0; i<jsonArray.size(); i++) {
            long uid = jsonArray.getLong(i);
            if (uid != userId) {
                userList.add(uid);// 过滤掉自己
            }
        }
        long createrId = serverFeast.getUserId();// 举办者,座位列表中没有举办者
        if (userId != createrId && !Tool.isInList(userList, createrId)){
            userList.add(createrId);
        }
        options.addHeader("ulist", userList.toString());

        // 推送内容
        JsonObject jsonObject = ChatManager.takeResponseData(chatBuilder);
        eventBus.publish(address, jsonObject, options);// 广播
        logger.info("###publicFeastMessage userId:" + userId + " feastId:" + serverFeast.getId() + " jsonObject:" + jsonObject.toString() + " ulist:" + userList.toString());
    }

    /**
     * 广播聊天数据
     * @param userInfo
     * @param chatBuilder
     */
    public static void publicChatMessage(UserInfo userInfo, PBChatMsg.Builder chatBuilder) {
        long userId = userInfo.getId();
        int serverId = userInfo.getServerId();
        String address = EventBusConstant.getAddress(EventBusConstant.GATE_BROADCAST);
        EventBus eventBus = MainService.getVertx().eventBus();
        DeliveryOptions options = new DeliveryOptions();
        options.addHeader("suid", userId + "");// 发言者的userid,广播时过滤

        // 广播的对象
        JsonArray serverList = new JsonArray();//需要广播的服务器列表
        JsonArray userList = new JsonArray();//需要广播的玩家id列表
        if(chatBuilder.getChatType() == ChatManager.CHAT_TYPE_SERVER){
            //世界聊天--推送给本服玩家
            serverList.add(serverId);
            options.addHeader("slist", serverList.toString());
            userList.add(userId);// 过滤掉自己

        } else if (chatBuilder.getChatType() == ChatManager.CHAT_TYPE_UNION){
            //联盟聊天--推送给联盟成员
            UserUnion userUnion = UnionManager.getUserUnion(userId);
            long unionId = userUnion.getUnionId();
            List<UnionMember> unionMemberList = UnionManager.getUnionMemberList(unionId);
            for (UnionMember unionMember : unionMemberList) {
                long uid = unionMember.getUserId();
                if (uid != userId) {
                    userList.add(uid);// 过滤掉自己
                }
            }
            options.addHeader("ulist", userList.toString());
        } else if (chatBuilder.getChatType() == ChatManager.CHAT_TYPE_WORLD){
            //跨服聊天--战区聊天
            serverList = ServerManager.getWarZoneServerList(serverId);
            options.addHeader("slist", serverList.toString());
            userList.add(userId);// 过滤掉自己

        }
        // 推送内容
        JsonObject jsonObject = ChatManager.takeResponseData(chatBuilder);
        eventBus.publish(address, jsonObject, options);// 广播
        logger.info("###publicChatMessage userId:" + userId + " jsonObject:" + jsonObject.toString() + " options:" + options.toString());
    }

    /**
     * 给本服所有玩家进行广播,推送红点
     * @param builder 红点内容
     */
    public static void publicRedPointAllUser(UserInfo userInfo, CSGameSystemRedPointResponse.Builder builder) {
        JsonObject jsonObject = ResponseUtils.getPushResponseData(builder.build().toByteArray());
        JsonArray serverIdList = new JsonArray().add(userInfo.getServerId());
        publicAllUser(serverIdList, userInfo.getId(), jsonObject);
    }

    /**
     * 给本服所有玩家进行广播, 通知世界Boss第一名产生了
     * @param userInfo
     */
    public static void publicWorldBossTopAllUser(UserInfo userInfo) {
        CsGameWorld.CSGameWorldBossPushTopResponse.Builder builder = CsGameWorld.CSGameWorldBossPushTopResponse.newBuilder();
        builder.setNickName(userInfo.getUserName());
        JsonObject jsonObject = ResponseUtils.getWorldBossResponseData(builder.build().toByteArray());
        JsonArray serverIdList = new JsonArray().add(userInfo.getServerId());
        publicAllUser(serverIdList, userInfo.getId(), jsonObject);
        logger.info("###publicWorldBossTopAllUser,topUserId:{}",userInfo.getId());
    }

    /**
     * 广播给指定服务器的所有人
     * @param serverIdList
     * @param userId 是否过滤该玩家 = 0表示不过滤
     * @param jsonObject 广播的内容
     */
    public static void publicAllUser(JsonArray serverIdList, long userId, JsonObject jsonObject) {
        String address = EventBusConstant.getAddress(EventBusConstant.GATE_BROADCAST);
        EventBus eventBus = MainService.getVertx().eventBus();
        DeliveryOptions options = new DeliveryOptions();
        if (userId > 0) {
            options.addHeader("suid", userId + "");// 是否过滤该玩家
        }
        options.addHeader("slist", serverIdList.toString());// 广播给指定服务器的所有人
        eventBus.publish(address, jsonObject, options);
    }

    /**
     * 广播给联盟其他成员
     * @param userInfo
     * @param unionId
     */
    public static void publicUnionHelp(UserInfo userInfo, long unionId, UnionReciprocityList unionReciprocityList) {
        long userId = userInfo.getId();
        String address = EventBusConstant.getAddress(EventBusConstant.GATE_BROADCAST);
        EventBus eventBus = MainService.getVertx().eventBus();
        DeliveryOptions options = new DeliveryOptions();
        options.addHeader("suid", userId + "");// 发言者的userid,广播时过滤
        JsonArray userList = new JsonArray();// 广播的对象

        List<UnionMember> unionMemberList = UnionManager.getUnionMemberList(unionId);
        for (UnionMember unionMember : unionMemberList) {
            long uid = unionMember.getUserId();
            if (uid != userId) {
                userList.add(uid);// 过滤掉自己
            }
        }
        options.addHeader("ulist", userList.toString());

        // 推送内容
        CSGameSystemPushDataResponse.Builder builder = CSGameSystemPushDataResponse.newBuilder();
        builder.getUserBuilder().getUnionBuilder().getUnionReciprocityInfoBuilder().putReciprocityList(unionReciprocityList.getId(),  UnionManager.takePBUnionReciprocityListInitBuilder(true, unionReciprocityList).build());
        JsonObject jsonObject = ResponseUtils.getPushResponseData(builder.build().toByteArray());
        eventBus.publish(address, jsonObject, options);// 广播
        logger.info("###publicUnionOtherMemberMessage userId:" + userId + " unionId:" + unionId + " jsonObject:" + jsonObject.toString() + " ulist:" + userList.toString());
    }

    /**
     * 广播给联盟其他成员 同步战力和城市收益，联盟建筑对城市收益有加成，联盟地标对战力有加成
     * @param userInfo
     * @param unionId
     */
    public static void publicUnionSyncUserPower(UserInfo userInfo, long unionId) {
        long userId = userInfo.getId();
        String address = EventBusConstant.getAddress(EventBusConstant.GATE_BROADCAST);
        EventBus eventBus = MainService.getVertx().eventBus();
        DeliveryOptions options = new DeliveryOptions();
        options.addHeader("suid", userId + "");// 发言者的userid,广播时过滤
        JsonArray userList = new JsonArray();// 广播的对象

        List<UnionMember> unionMemberList = UnionManager.getUnionMemberList(unionId);
        for (UnionMember unionMember : unionMemberList) {
            long uid = unionMember.getUserId();
            if (uid != userId) {
                userList.add(uid);// 过滤掉自己
            }
        }
        options.addHeader("ulist", userList.toString());

        // 推送内容
        CsGameSystem.CSGameSystemPushDataResponse.Builder response = CsGameSystem.CSGameSystemPushDataResponse.newBuilder();
        response.setType(ResponseUtils.PUSH_TIPS_TYPE_999);
        JsonObject jsonObject = ResponseUtils.getPushResponseData(response.build().toByteArray());// 广播给其他人的数据
        eventBus.publish(address, jsonObject, options);// 广播
        logger.info("###publicUnionSyncUserPower userId:" + userId + " unionId:" + unionId + " jsonObject:" + jsonObject.toString() + " ulist:" + userList.toString());
    }


    /**
     * 广播给联盟其他成员 同步战力和城市收益，联盟建筑对城市收益有加成，联盟地标对战力有加成
     * @param userId
     */
    public static void publicUnionSyncUserPower(long userId) {
        String address = EventBusConstant.getAddress(EventBusConstant.GATE_BROADCAST);
        EventBus eventBus = MainService.getVertx().eventBus();
        DeliveryOptions options = new DeliveryOptions();
        options.addHeader("suid", userId + "");// 发言者的userid,广播时过滤
        JsonArray userList = new JsonArray();// 广播的对象
        userList.add(userId);// 只推送指定的人
        options.addHeader("ulist", userList.toString());

        // 推送内容
        CsGameSystem.CSGameSystemPushDataResponse.Builder response = CsGameSystem.CSGameSystemPushDataResponse.newBuilder();
        response.setType(ResponseUtils.PUSH_TIPS_TYPE_999);
        JsonObject jsonObject = ResponseUtils.getPushResponseData(response.build().toByteArray());// 广播给其他人的数据
        eventBus.publish(address, jsonObject, options);// 广播
        logger.info("###publicUnionSyncUserPower userId:" + userId  + " jsonObject:" + jsonObject.toString() + " ulist:" + userList.toString());
    }




    /**
     * 广播给联盟其他成员
     * @param userInfo
     * @param unionId
     */
    public static void publicUnionMobileTask(UserInfo userInfo, long unionId, List<UnionMobileTaskInfo> taskInfoList) {
        long userId = userInfo.getId();
        String address = EventBusConstant.getAddress(EventBusConstant.GATE_BROADCAST);
        EventBus eventBus = MainService.getVertx().eventBus();
        DeliveryOptions options = new DeliveryOptions();
        options.addHeader("suid", userId + "");// 发言者的userid,广播时过滤
        JsonArray userList = new JsonArray();// 广播的对象

        List<UnionMember> unionMemberList = UnionManager.getUnionMemberList(unionId);
        for (UnionMember unionMember : unionMemberList) {
            long uid = unionMember.getUserId();
            if (uid != userId) {
                userList.add(uid);// 过滤掉自己
            }
        }
        options.addHeader("ulist", userList.toString());

        // 推送内容
        CSGameSystemPushDataResponse.Builder builder = CSGameSystemPushDataResponse.newBuilder();
        Common.PBUserData.Builder userBuilder = builder.getUserBuilder();
        for (UnionMobileTaskInfo mobileTaskInfo : taskInfoList) {
            ProtoDataUtils.updatePBUserData(userBuilder, mobileTaskInfo);
        }
        JsonObject jsonObject = ResponseUtils.getPushResponseData(builder.build().toByteArray());
        eventBus.publish(address, jsonObject, options);// 广播
        logger.info("###publicUnionMobileTask userId:" + userId + " unionId:" + unionId + " jsonObject:" + jsonObject.toString() + " ulist:" + userList.toString());
    }


    /**
     * 广播给联盟其他成员
     * @param userInfo
     * @param unionId
     */
    public static void publicUnionMobileTask(UserInfo userInfo, long unionId, UnionMobileTaskInfo taskInfo) {
        long userId = userInfo.getId();
        String address = EventBusConstant.getAddress(EventBusConstant.GATE_BROADCAST);
        EventBus eventBus = MainService.getVertx().eventBus();
        DeliveryOptions options = new DeliveryOptions();
        options.addHeader("suid", userId + "");// 发言者的userid,广播时过滤
        JsonArray userList = new JsonArray();// 广播的对象

        List<UnionMember> unionMemberList = UnionManager.getUnionMemberList(unionId);
        for (UnionMember unionMember : unionMemberList) {
            long uid = unionMember.getUserId();
            if (uid != userId) {
                userList.add(uid);// 过滤掉自己
            }
        }
        options.addHeader("ulist", userList.toString());

        // 推送内容
        CSGameSystemPushDataResponse.Builder builder = CSGameSystemPushDataResponse.newBuilder();
        Common.PBUserData.Builder userBuilder = builder.getUserBuilder();
        ProtoDataUtils.updatePBUserData(userBuilder, taskInfo);
        JsonObject jsonObject = ResponseUtils.getPushResponseData(builder.build().toByteArray());
        eventBus.publish(address, jsonObject, options);// 广播
        logger.info("###publicUnionMobileTask userId:" + userId + " unionId:" + unionId + " jsonObject:" + jsonObject.toString() + " ulist:" + userList.toString());
    }
}
